package cn.mz.frame.web.doc.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.util.Optional;

/**
 * @author shili
 * @date 2022/1/18
 */
@EnableSwagger2WebMvc
@EnableKnife4j
@EnableConfigurationProperties(SwaggerProperties.class)
@ConditionalOnProperty(prefix = SwaggerProperties.PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true)
public class SwaggerAutoConfiguration {

    @Bean
    public Docket defaultApi2(
            Environment environment,
            SwaggerProperties properties) {

        // 1. 获取项目名称
        String appName = environment.getProperty("spring.application.name");
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo(appName,properties))
                .select()
                .apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
                .paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo(@Nullable String appName, SwaggerProperties properties) {
        String defaultName = (appName == null ? "" : appName) + "应用";
        String title = Optional.ofNullable(properties.getTitle())
                .orElse(defaultName);
        String description = Optional.ofNullable(properties.getDescription())
                .orElse(defaultName);
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                .version(properties.getVersion())
                .contact(new Contact(properties.getContactUser(), properties.getContactUrl(), properties.getContactEmail()))
                .build();
    }

}
